package org.maxgroundstation.groundstation.comm.service;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * Contains the header and data for a service data fragment to be sent 
 * or which has been received.
 * @author Scott Davis
 * 
 * Copyright (C) 2010  Scott Davis
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
public class ServiceDataFragment {

	// Data members.
	private ServiceDataFragmentHeader header;
	private byte[] data;
	
	/**
	 * Constructor.
	 */
	public ServiceDataFragment() {
		header = new ServiceDataFragmentHeader();
		data = new byte[0];
	}
	
	/**
	 * Gets the fragment header.
	 * @return header.
	 */
	public ServiceDataFragmentHeader getHeader() {
		return header;
	}
	
	/**
	 * Sets the fragment header.
	 * @param header the new header.
	 */
	public void setHeader(ServiceDataFragmentHeader header) {
		this.header = header;
	}
	
	/**
	 * Gets the fragment data.
	 * @return data.
	 */
	public byte[] getData() {
		return data;
	}
	
	/**
	 * Sets the fragment data.
	 */
	public void setData(byte[] data) {
		this.data = data;
	}
	
	/**
	 * Gets the packet data for the fragment.
	 * @return the packet data.
	 */
	public byte[] toPacketData() {
		ByteBuffer buff = ByteBuffer.allocate(data.length + 40);
		buff.order(ByteOrder.LITTLE_ENDIAN);
		
		buff.putLong(header.getSyncHeader());
		buff.put(header.getServiceID().getBytes());
		buff.put(header.getClientID().getBytes());
		buff.putInt((int) header.getFrameLength());
		buff.putShort((short) header.getFragSize());
		buff.putShort((short) header.getFragNumber());
		buff.putLong(header.getTimestamp());
		buff.put(data);
		/*
		byte[] byteArray = buff.array();
		System.out.println("\n");
		for (int x = 0; x < byteArray.length; x++) {
			System.out.print(byteArray[x] + ",");
		}
		System.out.println("\n");
		*/
		return buff.array();
	}
}